"""
AdsenseMonitor.py
Copyright (C) otacon 2010 <orfeo18@gmail.com>

AdSense-Monitor is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

AdSense-Monitor is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
 
You should have received a copy of the GNU General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
"""

import Adsense
import sys
import threading
import time
import signal
import gobject

class ReportMonitor(threading.Thread,gobject.GObject):
    """
    This daemon will check, periodically, current status of your adsense
    stastistics (ecpm, earnings, clicks, ...)
    """
    __gsignals__ = {
    'status-changed' :
            (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
                (gobject.TYPE_INT,)),
    'report-changed' :
            (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE,
                (gobject.TYPE_PYOBJECT,)),
    }

    STATUS_OK = 0
    STATUS_UPDATE = 1
    STATUS_NO = -1
    
    def __init__(self):
        """Constructor for Adsense Daemon"""
        threading.Thread.__init__(self)
        gobject.GObject.__init__(self)
        self._adsense = Adsense.Adsense()
        self._event = threading.Event()
        self._username = None
        self._password = None
        self._autoupdate = False
        self._updaterate = 0.0
        self._quit = False
        self._login_valid = False
        self.set_status(ReportMonitor.STATUS_NO)

    def get_status(self):
        return self.status

    def set_status(self,status):
        if status != ReportMonitor.STATUS_OK and \
            status != ReportMonitor.STATUS_NO and \
            status != ReportMonitor.STATUS_UPDATE:
                return False
        else:
            self._status = status
            self.emit('status-changed', status )
            return True

    def set_update_rate(self,update_rate):
        self._updaterate = update_rate

    def set_auto_update(self,auto_update):
        self._autoupdate = auto_update

    def set_credentials(self , username = None , password = None):
        if username:
            self._username = username
        if password:
            self._password = password
        
        if self._username and self._password:
            self._login_valid=True

    def update(self):
        self._event.set()
        self._event.clear()

    def exit(self):
        self._quit = True
        self._event.set()

    def run(self):
        """Running the thread, updates periodically"""

        while not self._quit:
            if self._login_valid:
                self.set_status(ReportMonitor.STATUS_UPDATE)
                logged = self._adsense.login(self._username, self._password)
                if logged:
                    report = self._adsense.get_today()
                    self.set_status(ReportMonitor.STATUS_OK)
                    self._adsense.logout()
                    self.emit('report_changed',report.get_latest())
                else:
                    self.set_status(ReportMonitor.STATUS_NO)
            else:
                self.set_status(ReportMonitor.STATUS_NO)

            if self._autoupdate:
                timer = WatchDog(self._updaterate, self.update)
                timer.start()
            self._event.wait()
        sys.exit(0)

class WatchDog(threading.Thread):

    def __init__(self, updaterate, callback):
        threading.Thread.__init__(self)
        self.daemon = True
        self.exit = False
        self.callback = callback
        self._updaterate = updaterate

    def run(self):
        time.sleep(60*self._updaterate)
        if not self.exit:
            self.callback()
        sys.exit(0)

    def exit():
        self.exit = True
        
